﻿using Blm.Utils.Extensions;
using Language.Resource;
using Microsoft.Extensions.Localization;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;
using VisionCloud.Domain.UnitOfWork;

namespace VisionCloud.Service.Sys
{
    public class RoleService
    {
        public IUnitOfWork UnitOfWork { get; set; }
        public IStringLocalizer<ServiceResource> Localizer { get; set; }
        public ISysUserRepository SysUserRepository { get; set; }
        public ISysRoleRepository SysRoleRepository { get; set; }
        public ISysMenuFuncRepository SysMenuFuncRepository { get; set; }
        public ISysRolePermissionRepository SysRolePermissionRepository { get; set; }

        #region 角色

        public async Task<bool> Existed(SysRoleDto model)
        {
            return await SysRoleRepository.AnyAsync(p => (p.Name.ToLower() == model.Name.ToLower() || p.Code.ToLower() == model.Code.ToLower()));
        }

        public async Task<ApiPageResult> GetPage(SysRoleCondition conditon)
        {
            return await SysRoleRepository.GetPage(conditon);
        }

        public async Task CreateRole(SysRoleDto model, Guid opeId)
        {
            var exists = await Existed(model);
            if (exists == true)
            {
                throw new OperationException(Localizer["YB0223"].Value);
            }

            var entity = model.CopyTo<SysRole>();
            entity.RoleId = Guid.NewGuid();
            entity.CreatedBy = opeId;
            entity.CreatedDate = DateTime.Now;
            entity.LastUpdatedBy = opeId;
            entity.LastUpdatedDate = DateTime.Now;
            entity.Status = model.Status;

            SysRoleRepository.Add(entity);

            #region 添加角色的权限

            if (model.RoleMenuPermisions != null && model.RoleMenuPermisions.Count > 0)
            {
                /*
                 * 1.创建菜单功能：默认拥有四类功能，新增、编辑、删除、查看
                 * 2.创建功能与角色关系
                 */

                var funcList = new List<SysMenuFunc>();
                #region 添加菜单的功能项目

                foreach (var p in model.RoleMenuPermisions)
                {
                    SysMenuFunc sysMenuFunc = new SysMenuFunc()
                    {
                        MenuFuncId = Guid.NewGuid(),
                        MenuId = p.MenuId,
                        Name = p.MenuFuncName,
                        Description = p.Description,
                        Component = p.MenuFuncComponent,
                        Icon = p.MenuIcon,
                        Apis = p.FuncType,
                        Status = 0
                    };
                    funcList.Add(sysMenuFunc);
                }
                SysMenuFuncRepository.AddRange(funcList);

                #endregion 添加菜单的功能项目

                #region 添加功能与角色的关系

                //先删除旧的
                var roleFuncList = new List<SysRolePermission>();
                foreach (var p in funcList)
                {
                    SysRolePermission sysRolePermission = new SysRolePermission();
                    sysRolePermission.RolePermissionId = Guid.NewGuid();
                    sysRolePermission.RoleId = entity.RoleId;
                    sysRolePermission.MenuFuncId = p.MenuFuncId;

                    roleFuncList.Add(sysRolePermission);
                }

                SysRolePermissionRepository.AddRange(roleFuncList);

                #endregion 添加功能与角色的关系
            }

            #endregion 添加角色的权限

            await UnitOfWork.SaveChangesAsync();
        }

        public async Task DeleteRole(Guid roleId, Guid opeId)
        {
            var sysRole = SysRoleRepository.GetById(roleId);
            if (sysRole == null)
            {
                throw new OperationException(Localizer["YB0224"].Value);
            }
            SysRoleRepository.Update(t => t.RoleId == roleId, d =>
            {
                d.IsDeleted = true;
                d.RoleId = roleId;
                d.LastUpdatedBy = opeId;
                d.LastUpdatedDate = DateTime.Now;
            });

            await UnitOfWork.SaveChangesAsync();
        }

        public async Task UpdateRole(SysRoleDto model, Guid opeId)
        {
            var sysRole = SysRoleRepository.GetById(model.RoleId);
            if (sysRole == null)
            {
                throw new OperationException(Localizer["YB0224"].Value);
            }

            #region 更新角色的权限

            if (model.RoleMenuPermisions != null && model.RoleMenuPermisions.Count > 0)
            {
                /*
                 * 1.创建菜单功能：默认拥有四类功能，新增、编辑、删除、查看，以字符串格式存放在Component字段
                 * 2.创建功能与角色关系
                 */

                var funcList = new List<SysMenuFunc>();

                #region 添加菜单的功能项目

                foreach (var p in model.RoleMenuPermisions)
                {
                    SysMenuFunc sysMenuFunc = new SysMenuFunc()
                    {
                        MenuFuncId = Guid.NewGuid(),
                        MenuId = p.MenuId,
                        Name = p.MenuFuncName,
                        Description = p.Description,
                        Component = p.MenuFuncComponent,
                        Icon = p.MenuIcon,
                        Apis = p.FuncType,
                        Status = 0
                    };
                    funcList.Add(sysMenuFunc);
                }
                SysMenuFuncRepository.AddRange(funcList);

                #endregion 添加菜单的功能项目

                #region 添加功能与角色的关系

                var roleFuncList = new List<SysRolePermission>();
                foreach (var p in funcList)
                {
                    SysRolePermission sysRolePermission = new SysRolePermission();
                    sysRolePermission.RoleId = model.RoleId;
                    sysRolePermission.MenuFuncId = p.MenuFuncId;

                    roleFuncList.Add(sysRolePermission);
                }

                SysRolePermissionRepository.AddRange(roleFuncList);

                #endregion 添加功能与角色的关系
            }

            #endregion 更新角色的权限

            SysRoleRepository.Update(t => t.RoleId == model.RoleId,
(Action<SysRole>)(d =>
{
    d.Name = model.Name;
    d.Status = (SysRole.EnumRoleStatus?)model.Status;
    d.Description = model.Description;
    d.IsSuperAdministrator = model.IsSuperAdministrator;
    d.Code = model.Code;
    d.LastUpdatedBy = opeId;
    d.LastUpdatedDate = DateTime.Now;
}));
            await UnitOfWork.SaveChangesAsync();
        }

        public SysRoleDto FindRole(SysRoleDto sysRoleDto)
        {
            return SysRoleRepository.FindSysRole(sysRoleDto);
        }

        #endregion 角色
    }
}